import 'package:flutter/material.dart';

/// 暂未引用
/// 
/// 参考：https://juejin.cn/post/7205826220063031353
class SingleDragGridView<T extends Object> extends StatefulWidget {

  final List<T> dataList;
  final Widget Function(BuildContext contex, int index, T data) itemBuilder;
  final SliverGridDelegate gridDelegate;
  final Function(List<T> newList) onChanged;

  final ScrollPhysics? physics;
  final bool? shrinkWrap;
  final Axis? scrollDirection;
  final EdgeInsetsGeometry? padding;

  const SingleDragGridView({
    super.key,
    required this.gridDelegate,
    required this.itemBuilder,
    required this.dataList,
    required this.onChanged,
    this.physics,
    this.shrinkWrap,
    this.scrollDirection,
    this.padding
  });

  @override
  State<StatefulWidget> createState() => _SingleDragGridViewState<T>();
}

class _SingleDragGridViewState<T extends Object> extends State<SingleDragGridView<T>> {

  List<T> dataList = [];
  T? movingData;

  @override
  void initState() {
    super.initState();
    dataList.addAll(widget.dataList);
  }

  @override
  void didUpdateWidget(covariant SingleDragGridView<T> oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (dataList != widget.dataList) dataList = [...widget.dataList];
  }

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      padding: widget.padding,
      gridDelegate: widget.gridDelegate,
      physics: widget.physics,
      shrinkWrap: widget.shrinkWrap ?? true,
      scrollDirection: widget.scrollDirection ?? Axis.vertical,
      itemBuilder: (context, index) {
        return draggableItem(context, index);
      },
      itemCount: dataList.length,
    );
  }


  // 生成可拖动的item
  Widget draggableItem(BuildContext context, int index) {
    T data = dataList[index];

    return LongPressDraggable(
      data: data,
      feedback: Transform(
        transform: Matrix4.identity()..scale(1.1, 1.1),
        alignment: Alignment.center,
        child: widget.itemBuilder(context, index, data),
      ),
      childWhenDragging: null,
      onDragStarted: () {
        setState(() {
          //记录开始拖拽的数据
          movingData = data;
        });
      },
      onDraggableCanceled: (Velocity velocity, Offset offset) {
        setState(() {
          //清空标记进行重绘
          movingData = null;
        });
      },
      child: DragTarget<T>(
        builder: (context, candidateData, rejectedData) {
          return movingData == data ? Container() : widget.itemBuilder(context, index, data);
        },
        onWillAccept: (moveData) {
          var accept = moveData != null;
          if (accept) {
            exchangeItem(moveData, data);
          }
          return accept;
        },
        onAccept: (moveData) {
          movingData = null;
          exchangeItem(moveData, data);
        },
      ),
    );
  }

  // 重新排序
  void exchangeItem(T moveData, T toData) {
    setState(() {
      int toIndex = dataList.indexOf(toData);
      dataList.remove(moveData);
      dataList.insert(toIndex, moveData);
    });
    widget.onChanged(dataList);
  }

}
